package cn.hl.service.impl;

import cn.hl.domain.PurchaseApply;
import cn.hl.domain.PurchaseLog;
import cn.hl.dto.StockDto;
import cn.hl.enums.GlobalExceptionCode;
import cn.hl.feign.StockService;
import cn.hl.mapper.PurchaseApplyMapper;
import cn.hl.properties.VariablePurchase;
import cn.hl.service.IPurchaseApplyService;
import cn.hl.service.IPurchaseLogService;
import cn.hl.util.AssertUtil;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hulan
 * @since 2022-09-29
 */
@Service
public class PurchaseApplyServiceImpl extends ServiceImpl<PurchaseApplyMapper, PurchaseApply> implements IPurchaseApplyService {

    @Autowired
    private PurchaseApplyMapper purchaseApplyMapper;

    @Autowired
    private VariablePurchase variablePurchase;

    @Autowired
    private IPurchaseLogService purchaseLogService;

    @Autowired
    private StockService stockService;

    @Override
    public void approvalPurchaseReceipt(Long id, Integer status) {
        AssertUtil.isNotNull(id, GlobalExceptionCode.PARAM_NOT_ERROR);
        AssertUtil.isNotNull(status, GlobalExceptionCode.PARAM_NOT_ERROR);
        if (status == variablePurchase.getProcurement_completed()) {
            savePurchaseLog(id);
            inbound(id);
        }
        purchaseApplyMapper.updateByApplyId(id,status);
    }

    private void inbound(Long id) {
        PurchaseApply purchaseApply = selectById(id);
        StockDto stockDto = new StockDto();
        stockDto.setStatus(variablePurchase.getInbound());
        stockDto.setCount(purchaseApply.getCount());
        stockDto.setProductId(purchaseApply.getProductId());
        stockService.inboundAndOutbound(stockDto);
    }

    private void savePurchaseLog(Long id) {
        PurchaseApply purchaseApply = selectById(id);
        PurchaseLog purchaseLog = new PurchaseLog();
        purchaseLog.setProductId(purchaseApply.getProductId());
        purchaseLog.setProductName(purchaseApply.getProductName());
        purchaseLog.setCount(purchaseApply.getCount());
        purchaseLog.setCreateTime(new Date());
        purchaseLogService.insert(purchaseLog);
    }

}
